const dayjs = require('dayjs')

export const weeks = ['周日','周一','周二','周三','周四','周五','周六']
/**
 * 获取距离当前时间间隔
 * @param {*} time 
 */
export const getTimeDistance = (time) => {
    if (typeof time == "number" || Number(time) == time) {
        if (String(time).length == 10) {
            time = Number(time) * 1000
        } else if (String(time).length == 13) {
            time = Number(time)
        } else {
            console.log("时间格式错误");
            return time;
        }
    } else {
        if (typeof time == "string" && time.split(" ").length == 2 && time.split(/[- : \/]/).length == 6) {
            time = new Date(time.replace(/\-/g, '/')).getTime();
        } else {
            console.log("时间格式错误");
            return time;
        }
    }
 
    // 处理之后的time为13位数字格式的毫秒数
 
    var date_now = new Date();
    var date_time = new Date(time);
    var distance = date_now.getTime() - time;
 
    var days = parseInt(distance / (1000 * 60 * 60 * 24));
    if (days == 1) {
        return "昨天"
    } else if (days > 1 && days < 4) {
        return days + "天前";
    } else if (days > 3) {
        // 超过3天的，返回日期，如 2018-12-05
        // 如果是今年的，就省去年份，返回 12-05
        var year = date_time.getFullYear();
        var month = date_time.getMonth() + 1;
        if (month < 10) {
            month = "0" + month;
        }
        var day = date_time.getDate();
        if (day < 10) {
            day = "0" + day;
        }
        if (date_now.getFullYear() == year) {
            return month + "-" + day;
        } else {
            return year + "-" + month + "-" + day;
        }
    }
 
    var hours = parseInt((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    if (hours > 0) {
        return hours + "小时前";
    }
 
    var minutes = parseInt((distance % (1000 * 60 * 60)) / (1000 * 60));
    if (minutes > 0) {
        return minutes + "分钟前";
    };
 
    return "刚刚";
}

/**
 * 时间格式化
 * @param {*} timestamp 
 * @param {*} format 
 */
export const formatDate = (date = 0, format = 'YYYY-MM-DD HH:mm:ss') => {
    date = new Date(+date)
    if (/(Y+)/.test(format)) {
      format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
      'M+': date.getMonth() + 1,
      'D+': date.getDate(),
      'H+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    };
    for (let k in o) {
      if (new RegExp(`(${k})`).test(format)) {
        let str = o[k] + '';
        format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length));
      }
    }
    return format;
}

export const dateDistance = (dateStr,format='YYYY-MM-DD') =>{
    const dayLabel = ['前天','昨天','今天','明天','后天']
    const distince = dayjs(dateStr).diff(dayjs(),'day')
    if(distince >= -2 && distince <=2){
        return dayLabel[distince + 2]
      }else{
        return dayjs(dateStr).format(format)
      }
}

export default dayjs